import React, { useCallback, useRef } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router'
import styled from 'styled-components'
import { vscode } from '../utils/vscode'
import { MessageType } from '../../../src/utils/MessageHandler'
const BoxWrap = styled.div`
  border: 1px solid #ccc;
	border-radius: 5px;
`

const ToolbarWrap = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px;
  background-color: transparent;
`

const Flex1 = styled.div`
  flex: 1;
`

export const Toolbar = React.memo(function() {

  return (
    <ToolbarWrap>
      <vscode-button>@</vscode-button>
      <Flex1 />
      <vscode-button type='submit'>发送</vscode-button>
    </ToolbarWrap>
  )
})

export const ChatBoxContext = React.memo(function() {
  return (
    <div></div>
  )
})

export default function ChatInputBox() {
  const formRef = useRef<HTMLFormElement>(null);
	const navigate = useNavigate()
  const location = useLocation()
  const params = useParams();
	const handleSendMessage = useCallback((e: React.FormEvent<HTMLFormElement>, formRef: React.RefObject<HTMLFormElement | null>) => {
    e.preventDefault();
    e.stopPropagation();
    if(!formRef.current?.checkValidity()) {
			return
		}
    const formData = new FormData(formRef.current!);
    const value = formData.get('value')
    if(value === null) {
      return;	
    }
    if(location?.pathname.startsWith('/chat/')) {
    	vscode.postMessage({
        type: MessageType.sendMessageToLLM,
        data: {
          taskId: params.taskId,
          message: [
            {
              role: 'user',
              content: value
            }
          ]
        }
      })
    } else {
      const taskId = Date.now() + (Math.random() * 999999).toFixed(0).padStart(6, '0');
      vscode.postMessage({
        type: MessageType.sendMessageToLLM,
        data: {
          taskId: taskId,
          message: [
            {
              role: 'user',
              content: value
            }
          ]
        }
      })
      navigate('/chat/'+taskId, {
        state: {
          taskId: taskId,
          message: [
            {
              role: 'user',
              content: value
            }
          ]
        }
      })
    }
	}, [location?.pathname, navigate, params.taskId])
	

  return (
    <BoxWrap>
			<ChatBoxContext />
      <form ref={formRef} onSubmit={(e) => handleSendMessage(e, formRef)}>
        <vscode-textarea placeholder='请输入内容' name='value' style={{ width: '100%', height: '60px' }}></vscode-textarea>
        <Toolbar></Toolbar>
      </form>
    </BoxWrap>
  )
}
